package com.um.springboot.starter.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.um.springboot.starter.constants.SmsConsts;
import com.um.springboot.starter.properties.TencentSmsProperties;
import com.um.springboot.starter.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Objects;

/**
 * 腾讯云短信
 *
 * @author 甘天伟
 * @since 2024/5/7
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component(SmsConsts.TENCENT_IMPL)
public class TencentSmsServiceImpl implements SmsService {

    @Autowired
    TencentSmsProperties tencentSmsProperties;

    /**
     * 发送短信
     *
     * @param mobileAreaCode 国家代码
     * @param mobile         手机号
     * @param template       模板
     * @param params         模板参数
     * @param customSmsProps 自定义配置
     * @return 是否成功
     */
    @Override
    public boolean send(String mobileAreaCode, String mobile, String template, LinkedHashMap<String, String> params, Object customSmsProps) {
        TencentSmsProperties props = ObjectUtil.defaultIfNull((TencentSmsProperties) customSmsProps, tencentSmsProperties);

        Credential cred = new Credential(props.getSecretId(), props.getSecretKey());
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setReqMethod("POST");
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        SmsClient client = new SmsClient(cred, props.getRegionId(), clientProfile);

        SendSmsRequest request = new SendSmsRequest();
        request.setSmsSdkAppId(props.getAppId());

        String signName, templateCode;
        if (StrUtil.isBlank(mobileAreaCode) || ReUtil.isMatch("(\\+|00)?86", mobileAreaCode)) { // 国内短信
            signName = props.getSignName();
            templateCode = props.getTemplateCodes().get(template);
        } else { // 国际短信
            signName = props.getSignNameIntl();
            templateCode = props.getTemplateCodesIntl().get(template);
        }

        String phone = mobileAreaCode + mobile;
        request.setPhoneNumberSet(new String[]{phone});
        request.setSignName(signName);
        request.setTemplateId(templateCode);
        request.setTemplateParamSet(params.values().toArray(new String[0]));

        try {
            SendSmsResponse response = client.SendSms(request);
            if (null == response || null == response.getSendStatusSet() || 0 == response.getSendStatusSet().length) {
                log.error("腾讯云发送短信未响应: [{}]", phone);
                return false;
            }

            String result = SendSmsResponse.toJsonString(response);
            if (!Objects.equals(response.getSendStatusSet()[0].getCode(), "Ok")) {
                log.error("腾讯云发送短信失败: [{}]{}", phone, result);
                return false;
            }

            log.info("腾讯云发送短信结果: [{}]{}", phone, result);
            return true;
        } catch (Exception e) {
            log.error(StrUtil.format("腾讯云发送短信错误: [{}]", phone), e);
            return false;
        }
    }
}
